<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <!-- 输入搜索内容 -->
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            v-model="info.query"
            clearable
            @clear="getUserList"
          ></el-input>
        </el-col>
        <!-- 搜索 -->
        <el-col :span="10">
          <el-button type="primary" icon="el-icon-search" @click="getUserList"
            >搜索</el-button
          >
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe style="width: 100%">
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="用户名" width="150">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="150">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="150">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="150">
        </el-table-column>
        <el-table-column label="状态" width="150">
          <template slot-scope="scope">
            <!-- scope可以获取row的数据 -->
            <!-- switch表示开关，v-model的值为布尔值 -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatuschane(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- scope可以获取row的数据 -->
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              circle
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              circle
              @click="removeUserByID(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                circle
                @click="setrolesShow(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页模块 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="info.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="info.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <el-form
          ref="addFormRef"
          :model="addform"
          :rules="addRules"
          label-width="70px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addform.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addform.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addform.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addform.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editdialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <el-form
          ref="editFormRef"
          :model="editform"
          :rules="editRules"
          label-width="70px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editform.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editform.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editform.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setroledialogVisible"
        width="50%"
        @close="setroledialogClose"
      >
        <div>
          <p>当前的用户 : {{ userinfo.username }}</p>
          <p>当前的角色 : {{ userinfo.role_name }}</p>
          <p>
            分配新角色 :
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolelist"
                :key="item.id"
                :value="item.id"
                :label="item.roleName"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setroledialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',

  data() {
    // 效验邮箱规则
    var checkEamil = (rule, value, callback) => {
      let re = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/
      if (!re.test(value)) {
        return callback(new Error('请输入正确的邮箱地址'))
      }
      callback()
    }
    var checkmobile = (rule, value, callback) => {
      let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (!reg.test(value)) {
        return callback(new Error('请输入正确的手机号'))
      }
      callback()
    }

    return {
      // 查询到的用户数据
      userlist: [],
      // 总记录数
      total: 0,
      // 控制添加用户对话框是否隐藏
      dialogVisible: false,
      // 控制编辑用户对话框是否隐藏
      editdialogVisible: false,
      // 查询用户信息的参数
      info: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 要添加用户的表单数据
      addform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户的验证规则对象
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEamil, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 查询到的用户信息对象
      editform: {},
      // 修改表单的验证规则对象
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],

        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEamil, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 分配角色对话框是否隐藏
      setroledialogVisible: false,
      // 即将分配角色的用户
      userinfo: {},
      // 所有角色列表
      rolelist: [],
      // 已选中的即将分配的角色ID
      selectedRoleId: ' '
    }
  },
  created() {
    // 获取用户列表数据
    this.getUserList()
  },
  methods: {
    // 获取用户列表页
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.info
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户数据失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // 每页显示条数改变时，将改变后每页显示的条数重新赋值给请求参数
    handleSizeChange(val) {
      // 选择每页显示条数后，将其值重新赋给请求用户列表的参数info
      this.info.pagesize = val
      // 携带更新后的参数重新发送获取用户列表请求
      this.getUserList()
      console.log(val)
    },
    // 当前页改变时，将改变后的数据重新赋值给请求参数
    handleCurrentChange(val) {
      this.info.pagenum = val
      this.getUserList()
      console.log(val)
    },
    // 用户状态发生改变,发送修改用户状态请求
    async userStatuschane(user) {
      console.log(user.mg_state)
      const { data: res } = await this.$http.put(
        `users/${user.id}/state/${user.mg_state}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$message.error('修改用户状态失败')
      }
      this.$message.success('修改状态成功')
    },
    // 关闭对话框重置表单
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确认添加用户
    addUser() {
      // 表单预验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        // 发送添加用户请求
        const { data: res } = await this.$http.post('users', this.addform)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 控制添加用户对话框是否隐藏
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 点击修改按钮，显示编辑用户对话框，发送查询用户信息请求，将用户信息渲染到页面
    async showEditDialog(id) {
      this.editdialogVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      console.log(res)
      this.editform = res.data
    },
    // 点击确认按钮，发送修改用户请求，修改用户信息
    editUser() {
      // 表单预验证
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 发送修改用户请求
        const { data: res } = await this.$http.put(
          'users/' + this.editform.id,
          {
            email: this.editform.email,
            mobile: this.editform.mobile
          }
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑用户失败')
        }
        this.editdialogVisible = false
        this.getUserList()
        this.$message.success('编辑用户成功')
      })
    },
    // 关闭编辑用户对话框重置表单
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 根据用户ID删除用户
    async removeUserByID(id) {
      // confirm为删除弹框方法
      await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 发送删除用户请求
          const { data: res } = await this.$http.delete(`users/${id}`)
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击分配角色显示分配角色对话框
    async setrolesShow(user) {
      // console.log(user)
      this.userinfo = user
      this.setroledialogVisible = true
      // 获取所有角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.rolelist = res.data
    },
    // 点击按钮，分配角色
    async setRole() {
      // 如果没有选择角色
      if (!this.selectedRoleId) {
        return this.$message.error('请选择需要分配的角色')
      }
      // // 分配角色
      const body = {
        rid: this.selectedRoleId
      }
      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        body
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.setroledialogVisible = false
    },
    // 关闭分配角色对话框
    setroledialogClose() {
      // 让被选中的角色ID为空
      this.selectedRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
</style>
